<template>
<!--  <div style="position: absolute; top: 0">-->
<!--    <input id="uploadBtn" type="file" @change="loadExcel" />-->

<!--    <span>Or Load remote xlsx file:</span>-->

<!--    <select v-model="selected" @change="selectExcel">-->
<!--      <option disabled value="">Choose</option>-->
<!--      <option v-for="option in options" :key="option.text" :value="option.value">-->
<!--        {{ option.text }}-->
<!--      </option>-->
<!--    </select>-->

<!--    <a href="javascript:void(0)" @click="downloadExcel">Download source xlsx file</a>-->
<!--  </div>-->
  <div id="luckysheet"></div>
  <div v-show="isMaskShow" id="tip">Downloading</div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { exportExcel } from './export'
import LuckyExcel from 'luckyexcel'

const isMaskShow = ref(false)
const selected = ref('')
const jsonData = ref({})
const options = ref([
  { text: 'Money Manager.xlsx', value: 'https://minio.cnbabylon.com/public/luckysheet/money-manager-2.xlsx' },
  {
    text: 'Activity costs tracker.xlsx',
    value: 'https://minio.cnbabylon.com/public/luckysheet/Activity%20costs%20tracker.xlsx'
  },
  {
    text: 'House cleaning checklist.xlsx',
    value: 'https://minio.cnbabylon.com/public/luckysheet/House%20cleaning%20checklist.xlsx'
  },
  {
    text: 'Student assignment planner.xlsx',
    value: 'https://minio.cnbabylon.com/public/luckysheet/Student%20assignment%20planner.xlsx'
  },
  {
    text: 'Credit card tracker.xlsx',
    value: 'https://minio.cnbabylon.com/public/luckysheet/Credit%20card%20tracker.xlsx'
  },
  { text: 'Blue timesheet.xlsx', value: 'https://minio.cnbabylon.com/public/luckysheet/Blue%20timesheet.xlsx' },
  {
    text: 'Student calendar (Mon).xlsx',
    value: 'https://minio.cnbabylon.com/public/luckysheet/Student%20calendar%20%28Mon%29.xlsx'
  },
  {
    text: 'Blue mileage and expense report.xlsx',
    value: 'https://minio.cnbabylon.com/public/luckysheet/Blue%20mileage%20and%20expense%20report.xlsx'
  }
])

const loadExcel = (evt) => {
  const files = evt.target.files
  if (files == null || files.length == 0) {
    alert('No files wait for import')
    return
  }

  let name = files[0].name
  let suffixArr = name.split('.'),
    suffix = suffixArr[suffixArr.length - 1]
  if (suffix != 'xlsx') {
    alert('Currently only supports the import of xlsx files')
    return
  }
  LuckyExcel.transformExcelToLucky(files[0], function (exportJson, luckysheetfile) {
    if (exportJson.sheets == null || exportJson.sheets.length == 0) {
      alert('Failed to read the content of the excel file, currently does not support xls files!')
      return
    }
    console.log('exportJson', exportJson)
    jsonData.value = exportJson

    window.luckysheet.destroy()

    window.luckysheet.create({
      container: 'luckysheet', //luckysheet is the container id
      showinfobar: false,
      data: exportJson.sheets,
      title: exportJson.info.name,
      userInfo: exportJson.info.name.creator
    })
  })
}
const selectExcel = (evt) => {
  const value = selected.value
  const name = evt.target.options[evt.target.selectedIndex].innerText

  if (value == '') {
    return
  }
  isMaskShow.value = true

  LuckyExcel.transformExcelToLuckyByUrl(value, name, (exportJson, luckysheetfile) => {
    if (exportJson.sheets == null || exportJson.sheets.length == 0) {
      alert('Failed to read the content of the excel file, currently does not support xls files!')
      return
    }
    console.log('exportJson', exportJson)
    jsonData.value = exportJson

    isMaskShow.value = false
    window.luckysheet.destroy()

    window.luckysheet.create({
      container: 'luckysheet', //luckysheet is the container id
      showinfobar: false,
      data: exportJson.sheets,
      title: exportJson.info.name,
      userInfo: exportJson.info.name.creator
    })
  })
}
const downloadExcel = () => {
  // const value = selected.value;;
  //
  // if(value.length==0){
  //     alert("Please select a demo file");
  //     return;
  // }
  //
  // var elemIF = document.getElementById("Lucky-download-frame");
  // if(elemIF==null){
  //     elemIF = document.createElement("iframe");
  //     elemIF.style.display = "none";
  //     elemIF.id = "Lucky-download-frame";
  //     document.body.appendChild(elemIF);
  // }
  // elemIF.src = value;
  exportExcel(luckysheet.getAllSheets(), '下载')
}

// !!! create luckysheet after mounted
onMounted(() => {
    const sheets = [
        {
            "name": "第一个工作表", //Worksheet name
            "color": "#eee333", //Worksheet color
            "index": 0, //Worksheet index
            "status": 1, //Worksheet active status
            "order": 0, //The order of the worksheet
            "hide": 0,//Whether worksheet hide
            "row": 36, //the number of rows in a sheet
            "column": 10, //the number of columns in a sheet
            "defaultRowHeight": 120, //Customized default row height
            "defaultColWidth": 200, //Customized default column width
            "celldata": [], //Initial the cell data
            "config": {
                "merge":{}, //merged cells
                "rowlen":{}, //Table row height
                "columnlen":{}, //Table column width
                "rowhidden":{}, //hidden rows
                "colhidden":{}, //hidden columns
                "borderInfo":{}, //borders
                "authority":{//当前工作表的权限配置
                    selectLockedCells:1, //选定锁定单元格
                    selectunLockedCells:1, //选定解除锁定的单元格
                    formatCells:1, //设置单元格格式
                    formatColumns:1, //设置列格式
                    formatRows:1, //设置行格式
                    insertColumns:1, //插入列
                    insertRows:1, //插入行
                    insertHyperlinks:1, //插入超链接
                    deleteColumns:1, //删除列
                    deleteRows:1, //删除行
                    sort:1, //排序
                    filter:1, //使用自动筛选
                    usePivotTablereports:1, //使用数据透视表和报表
                    editObjects:1, //编辑对象
                    editScenarios:1, //编辑方案
                    sheet:0, //如果为1或true，则该工作表受到保护；如果为0或false，则该工作表不受保护。
                    hintText:"单元格锁定，不可编辑！", //弹窗提示的文字
                    algorithmName:"None",//加密方案：MD2,MD4,MD5,RIPEMD-128,RIPEMD-160,SHA-1,SHA-256,SHA-384,SHA-512,WHIRLPOOL
                    saltValue:null, //密码解密的盐参数，为一个自己定的随机数值

                    // allowRangeList:[{ //区域保护
                    //     name:"area", //名称
                    //     password:"1", //密码
                    //     hintText:"", //提示文字
                    //     algorithmName:"None",//加密方案：MD2,MD4,MD5,RIPEMD-128,RIPEMD-160,SHA-1,SHA-256,SHA-384,SHA-512,WHIRLPOOL
                    //     saltValue:null, //密码解密的盐参数，为一个自己定的随机数值
                    //     sqref:"$C$1:$D$5" //区域范围
                    // }],
                }, //Worksheet protection
            },
            "scrollLeft": 0, //Left and right scroll bar position
            "scrollTop": 0, //Up and down scroll bar position
            "luckysheet_select_save": [], //selected area
            "calcChain": [],//Formula chain
            "isPivotTable":false,//Whether is pivot table
            "pivotTable":{},//Pivot table settings
            "filter_select": {},//Filter range
            "filter": 1,//Filter configuration
            "luckysheet_alternateformat_save": [], //Alternate colors
            "luckysheet_alternateformat_save_modelCustom": [], //Customize alternate colors
            "luckysheet_conditionformat_save": {},//condition format
            "frozen": {}, //freeze row and column configuration
            "chart": [], //Chart configuration
            "zoomRatio":1, // zoom ratio
            "image":[], //image
            "showGridLines": 1, //Whether to show grid lines
            dataVerification: {
                "0_0": {
                    "type": "dropdown",
                    "type2": "dropdown",
                    "value1": "符合,不符合",
                    "value2": "1,2,3",
                    "checked": true,
                    "remote": false,
                    "prohibitInput": false,
                    "hintShow": false,
                    "hintText": ""
                },
            }
        }];
    luckysheet.create({
        container: 'luckysheet', //luckysheet is the container id
        showinfobar: false,
        showsheetbar: true,
        enableAddRow: false,
        enableAddBackTop: false,
        showtoolbar: true,
        showstatisticBar: false,
        showstatisticBarConfig: {
            count: false, // 计数栏
            view: false, // 打印视图
            zoom: false, // 缩放
        },
        sheetFormulaBar: false,
        showtoolbarConfig: {
            undoRedo: false, //撤销重做，注意撤消重做是两个按钮，由这一个配置决定显示还是隐藏
            paintFormat: false, //格式刷
            currencyFormat: false, //货币格式
            percentageFormat: false, //百分比格式
            numberDecrease: false, // '减少小数位数'
            numberIncrease: false, // '增加小数位数
            moreFormats: false, // '更多格式'
            font: false, // '字体'
            fontSize: false, // '字号大小'
            bold: false, // '粗体 (Ctrl+B)'
            italic: false, // '斜体 (Ctrl+I)'
            strikethrough: false, // '删除线 (Alt+Shift+5)'
            underline: false, // '下划线 (Alt+Shift+6)'
            textColor: false, // '文本颜色'
            fillColor: false, // '单元格颜色'
            border: false, // '边框'
            mergeCell: false, // '合并单元格'
            horizontalAlignMode: false, // '水平对齐方式'
            verticalAlignMode: false, // '垂直对齐方式'
            textWrapMode: false, // '换行方式'
            textRotateMode: false, // '文本旋转方式'
            image:false, // '插入图片'
            link:false, // '插入链接'
            chart: false, // '图表'（图标隐藏，但是如果配置了chart插件，右击仍然可以新建图表）
            postil:  false, //'批注'
            pivotTable: false,  //'数据透视表'
            function: false, // '公式'
            frozenMode: false, // '冻结方式'
            sortAndFilter: false, // '排序和筛选'
            conditionalFormat: false, // '条件格式'
            dataVerification: false, // '数据验证'
            splitColumn: false, // '分列'
            screenshot: false, // '截图'
            findAndReplace: false, // '查找替换'
            protection:false, // '工作表保护'
            print:false, // '打印'
        },
        // 自定义配置单元格右击菜单
        cellRightClickConfig: {
        copy: true, // 复制
        copyAs: false, // 复制为
        paste: false, // 粘贴
        insertRow: true, // 插入行
        insertColumn: false, // 插入列
        deleteRow: true, // 删除选中行
        deleteColumn: false, // 删除选中列
        deleteCell: false, // 删除单元格
        hideRow: false, // 隐藏选中行和显示选中行
        hideColumn: true, // 隐藏选中列和显示选中列
        rowHeight: true, // 行高
        columnWidth: false, // 列宽
        clear: false, // 清除内容
        matrix: false, // 矩阵操作选区
        sort: false, // 排序选区
        filter: false, // 筛选选区
        chart: false, // 图表生成
        image: false, // 插入图片
        link: false, // 插入链接
        data: false, // 数据验证
        cellFormat: false // 设置单元格格式
        },
        // 自定义配置sheet页右击菜单
        sheetRightClickConfig: {
            delete: false, // 删除
            copy: false, // 复制
            rename: false, //重命名
            color: false, //更改颜色
            hide: false, //隐藏，取消隐藏
            move: false, //向左移，向右移
        },
        lang: 'zh', // 设定表格语言
        showsheetbarConfig: {
            add: false, //新增sheet
            // menu: false, //sheet管理菜单
            // sheet: false //sheet页显示
        },
        data: sheets

    })
})
</script>

<style  scoped>
#luckysheet {
  margin: 0px;
  padding: 0px;
  position: absolute;
  width: 100%;
  left: 0px;
  top: 30px;
  bottom: 0px;
}

#uploadBtn {
  font-size: 16px;
}

#tip {
  position: absolute;
  z-index: 1000000;
  left: 0px;
  top: 0px;
  bottom: 0px;
  right: 0px;
  background: rgba(255, 255, 255, 0.8);
  text-align: center;
  font-size: 40px;
  align-items: center;
  justify-content: center;
  display: flex;
}
</style>
